package com.dmall.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dmall.entity.Account;
import com.dmall.entity.Menue;
import com.dmall.pagedata.PageData;
import com.dmall.service.AccountService;
import com.dmall.service.MenuService;
import com.dmall.util.AjaxResponse;
import com.dmall.util.MD5Util;
import com.google.gson.Gson;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AccountService as = new AccountService();

    public LoginServlet() {
    	
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String op = "";
		if(request.getParameter("op")!=null) {
			op = request.getParameter("op");
		}
		if("login".equals(op)) {
			doLogin(request, response);			
		}else if("logout".equals(op)) {
			doLogout(request, response);
		}
	
	}
	protected void doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		request.getSession().removeAttribute("username");
		response.sendRedirect("/dmall/back/login.jsp");
	}
	protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 接收表单提交的数据，获取name="keywords"的值,
		String username = "";
		String password = "";
		username = request.getParameter("username");
		password = request.getParameter("password");
		//response.sendRedirect("/login.jsp");

		//将密码加密
		password = MD5Util.getEncodeByMd5(password);
		Account account = as.getAcount(username, password);
		AjaxResponse ar = new AjaxResponse();
		if(account!=null) {
			request.getSession().setAttribute("username", username);
			ar.setCode(1);
			ar.setMsg("登录成功");
			request.getSession().setAttribute("username", account.getAccount());
			System.out.println("登录成功");
		}else {
			ar.setCode(0);
			System.out.println("用户名或密码错误");
			ar.setMsg("用户名或密码错误");
		}
		Gson gson = new Gson();
		String str = gson.toJson(ar);
		
		out.print(str);
		out.close();
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
